//
//  HMNetworkTools.swift
//  Swift网络请求封装
//
//  Created by Apple on 16/9/18.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import AFNetworking



//  网络请求类型
enum RequestType {
    case GET
    case POST
}


class HMNetworkTools: AFHTTPSessionManager {

    //  全局访问点
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        //  添加可接受的响应数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")

        return tools
    }()
    
    fileprivate func request(type: RequestType, url: String, params: Any?, callBack:@escaping (Any?, Error?)->()) -> Void {
        
        
        if type == .GET {
            self.get(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response, nil)
                }, failure: { (_, error) in
                callBack(nil, error)
            })
        } else {
            self.post(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response, nil)
                }, failure: { (_, error) in
                callBack(nil, error)
            })
        }
        
    }
}

// MARK :-- 微博首页相关接口
extension HMNetworkTools {
    
    func requestStatuses(accessToken:String,callBack:@escaping (Any?, Error?) -> ()) {
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        let params = [
        
            "access_token":accessToken
            
        ]
        //print(url + "?access_token=\(accessToken)")
        
        request(type: .GET, url: url, params: params, callBack: callBack)
        
    }
    
}




extension HMNetworkTools {
    
    //通过accessToken 获取用户信息
    func requestUserInfo(accessToken:String,uid:Int64,callBack:@escaping (Any?, Error?) -> ()){
        let url = "https://api.weibo.com/2/users/show.json"
        let params: [String : Any] = [
            "access_token":accessToken,
            "uid":uid
        ] //as [String : Any]
        
        request(type: .GET, url: url, params: params, callBack: callBack)
        
    }
    
    
    //根据code 获取accessToken
    func requestAccessToken(code: String, callBack:@escaping (Any?,Error?) -> ()){
    
        let url = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id":WeiboAppKey,
            "client_secret":WeoboAppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WeiboRedirect_Uri
            
        ]
        
        request(type: .POST, url: url, params: params, callBack: callBack)
    
    }
    
    
}
